package com.yami.shop.api.controller;

import cn.hutool.core.util.ObjectUtil;
import com.yami.shop.bean.event.ProdRightsEvent;
import com.yami.shop.bean.model.ShopDetail;
import com.yami.shop.bean.param.EsProductParam;
import com.yami.shop.bean.vo.search.MicroreleaseProductSearchVo;
import com.yami.shop.common.exception.YamiShopBindException;
import com.yami.shop.common.response.ServerResponseEntity;
import com.yami.shop.common.util.EsPageVO;
import com.yami.shop.common.util.PageParam;
import com.yami.shop.mystery.common.dto.ActivityPresellDto;
import com.yami.shop.mystery.common.model.MysteryBox;
import com.yami.shop.mystery.common.service.ActivityPresellService;
import com.yami.shop.mystery.common.service.MysteryBoxService;
import com.yami.shop.search.common.param.EsPageParam;
import com.yami.shop.search.common.service.SearchMysteryBoxService;
import com.yami.shop.service.ChannelUserRelationRecordService;
import com.yami.shop.service.ShopDetailService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springdoc.api.annotations.ParameterObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * @author wxf
 * @date 2023/6/5 9:26
 */
@RestController
@RequestMapping("/box")
@Tag(name = "盲盒商品接口")
public class MysteryBoxController {

    @Autowired
    private MysteryBoxService mysteryBoxService;

    @Autowired
    private ActivityPresellService activityPresellService;

    @Autowired
    private SearchMysteryBoxService searchMysteryBoxService;

    @Autowired
    private ApplicationContext applicationContext;

    @Autowired
    private ChannelUserRelationRecordService channelUserRelationRecordService;

    @Autowired
    private ShopDetailService shopDetailService;

    /**
     * 功能描述: 未登录下 盲盒商品列表
     * @Author: LSR
     * @Date: 2023/4/19 18:50
     */
    @GetMapping("/microreleaseList")
    @Operation(summary =  "盲盒商品列表", description = "盲盒商品列表")
    public ServerResponseEntity<EsPageVO<MicroreleaseProductSearchVo>> microreleaseList(PageParam page, @ParameterObject EsProductParam productParam) {
        // 获取开启活动的活动ID
        List<ActivityPresellDto> activityPresellDtos = activityPresellService.selectAllActivityPresellByActivityType(3);
        // 根据ID转化为Map
        Map<Long, ActivityPresellDto> activityPresellMap = activityPresellDtos.stream().collect(Collectors.toMap(ActivityPresellDto::getId, Function.identity()));

        List<Long> activityIds = activityPresellDtos.stream().map(ActivityPresellDto::getId).collect(Collectors.toList());
        productParam.setActivityIds(activityIds);
        EsPageParam esPageParam = new EsPageParam();
        esPageParam.setCurrent((int) page.getCurrent());
        esPageParam.setSize((int) page.getSize());
        EsPageVO<MicroreleaseProductSearchVo> productPage = searchMysteryBoxService.microreleasePage(esPageParam, productParam, Boolean.FALSE);
        // 循环组装数据
        for (MicroreleaseProductSearchVo microreleaseProductSearchVo : productPage.getRecords()) {
            // 没有活动获取商品默认限购数
            microreleaseProductSearchVo.setRuleMaxNum(microreleaseProductSearchVo.getMaxNum());
            if (microreleaseProductSearchVo.getActivityId() != 0) {
                ActivityPresellDto activityPresellDto = activityPresellMap.get(microreleaseProductSearchVo.getActivityId());
                if (ObjectUtil.isNotEmpty(activityPresellDto)) {
                    if(ObjectUtil.isNotEmpty(activityPresellDto.getMaxNum()) && activityPresellDto.getMaxNum() > 0){
                        microreleaseProductSearchVo.setMaxNum(activityPresellDto.getMaxNum());
                    }
                    if(ObjectUtil.isNotEmpty(activityPresellDto.getRuleMaxNum()) && activityPresellDto.getRuleMaxNum() > 0){
                        microreleaseProductSearchVo.setRuleMaxNum(activityPresellDto.getRuleMaxNum());
                    }
                    microreleaseProductSearchVo.setStartTime(activityPresellDto.getPutawayTime());
                }
            }
        }
        return ServerResponseEntity.success(productPage);
    }

    @GetMapping("/getProdInfo")
    @Operation(summary =  "获取商品信息", description = "根据盲盒商品ID（prodId）获取盲盒商品信息")
    public ServerResponseEntity<MicroreleaseProductSearchVo> recommend(Long prodId,String userId) {
        MicroreleaseProductSearchVo productSearchVO = new MicroreleaseProductSearchVo();
        MysteryBox mysteryBox = mysteryBoxService.detail(prodId);
        if (mysteryBox == null || mysteryBox.getStatus() == 0) {
            // 商品已下线
            throw new YamiShopBindException("yami.product.off.shelves");
        }
        cn.hutool.core.bean.BeanUtil.copyProperties(mysteryBox, productSearchVO);
        productSearchVO.setProdId(mysteryBox.getId());
        productSearchVO.setProdName(mysteryBox.getBoxName());
        productSearchVO.setMold(2);
        productSearchVO.setAuthorName(mysteryBox.getAuthor());
        productSearchVO.setIssueName(mysteryBox.getIssue());
        productSearchVO.setCirculation(mysteryBox.getTotalStocks());
        productSearchVO.setTotalStocks(mysteryBox.getBoxSku().getActualStock().intValue());
        productSearchVO.setMaxNum(mysteryBox.getQuota().intValue());
        productSearchVO.setRuleMaxNum(mysteryBox.getQuota().intValue());

        productSearchVO.setIsRights(0);
        if (ObjectUtil.isNotEmpty(userId)) {
            // 该用户是否绑定链
            ShopDetail shopDetail = shopDetailService.getById(mysteryBox.getShopId());
            Boolean hasDTCAddress = channelUserRelationRecordService.isHasDTCAddress(userId, mysteryBox.getChain(), shopDetail.getChannelCode());
            productSearchVO.setIsHasDTCAddress(hasDTCAddress);
            productSearchVO.setChainCode(mysteryBox.getChain());
            productSearchVO.setChannelCode(shopDetail.getChannelCode());
            if(mysteryBox.getProdType() == 1){
                // 获取活动信息
                ProdRightsEvent prodRightsEvent = new ProdRightsEvent();
                prodRightsEvent.setProductSearchVO(productSearchVO);
                prodRightsEvent.setUserId(userId);
                applicationContext.publishEvent(prodRightsEvent);
            }
        }else {
            // 通过商品ID查活动信息
            List<ActivityPresellDto> activityPresellDtos = activityPresellService.selectAllActivityPresellByProdId(prodId);
            if(ObjectUtil.isNotEmpty(activityPresellDtos)){
                ActivityPresellDto activityPresellDto = activityPresellDtos.get(0);
                if(ObjectUtil.isNotEmpty(activityPresellDto)){
                    productSearchVO.setStartTime(activityPresellDto.getPutawayTime());
                    productSearchVO.setRuleMaxNum(activityPresellDto.getRuleMaxNum());
                }
            }
        }
        return ServerResponseEntity.success(productSearchVO);
    }

}
